import config from '@/config';
import { gotoPage } from './util';

/**
 * 发送请求
 */
function baseRequest(url : string, method : any, data : object, {
	noVerify = false
}) : any {
	let Url = config.HTTP_REQUEST_URL,
		header : any = {
			Accept: 'application/json, text/plain, */*',
			'Accept-Language': 'zh-CN,zh;q=0.9',
			server: true
		},
		token = uni.getStorageSync('token');

	if (token) header['ba-user-token'] = token;

	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + '/' + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res : any) => {
				if (noVerify) {
					reslove(res.data);
				} else if (res.data.code == 200) {
					reslove(res.data);
				} else {
					reject(res.data.msg || res.data.message || `系统错误`);
				}
			},
			fail: (msg) => {
				let data = {
					mag: `请求失败`,
					status: 1 //1没网
				}
				reject(data);
			}
		})
	});
}

const request = {
	get: (api : string, data ?: object, opt ?: any) => baseRequest(api, 'get', data, opt || {}),
	post: (api : string, data ?: object, opt ?: any) => baseRequest(api, 'post', data, opt || {}),
};

export default request;